package com.jushu.storbox.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.jushu.storbox.util.LogUtil;

import android.view.View;
import android.widget.BaseAdapter;

public abstract class AbsTemplateAdapter<T> extends BaseAdapter {

	private static final String TAG = AbsTemplateAdapter.class.getSimpleName();
	
	protected List<T> objectList = null;
	
	private Comparator<T> comparator;
	
	public AbsTemplateAdapter(List<T> translateList) {
		if(translateList == null){
			this.objectList = new ArrayList<T>();
		}else{
			this.objectList = translateList;
		}
	}
	
	@Override
	public int getCount() {
		if(objectList != null) {
			return objectList.size();
		}
		return 0; 
	}

	@Override
	public T getItem(int position) {
		if(objectList != null) {
			return objectList.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public interface IViewHolder<T> {
		public View getHolderView();
		public T getHolderDate();
		public void updataHolderView();
	}

	protected List<T> getObjectList() {
		return objectList;
	}
	
	public void sort(Comparator<T> comparator){
		this.comparator = comparator;
		doSort();
		notifyDataSetChanged();
	}
	
	protected Comparator<T> getComparator() {
		if(comparator == null) {
			comparator = getDefaultComparator();
		}
		return comparator;
	}
	
	protected Comparator<T> getDefaultComparator() {
		return new Comparator<T>() {
			@Override
			public int compare(Object lhs, Object rhs) {
				return 0;
			}
		};
	}
	
	private void doSort() {
		Collections.sort(objectList, getComparator());
	}
	
	public boolean contains(T data) {
		if(objectList == null) {
			return false;
		}
		if(data == null) {
			return false;
		} else {
			return objectList.contains(data);
		}
	}
	
	public void addData(T data) {
		if(data == null){
			return;
		}
		if(objectList != null) {
			this.objectList.add(data);
			notifyDataSetChanged();
		} else {
			LogUtil.e(TAG,"data list is null");
		}
	}
	
	public void addData(int index, T data) {
		if(data == null){
			return;
		}
		if(objectList != null) {
			this.objectList.add(index, data);
			notifyDataSetChanged();
		}else {
			LogUtil.e("E","data list is null");
		}
	}
	
	public void addDatas(List<T> datasList) {
		if(datasList == null){
			return;
		}
		this.objectList.addAll(datasList);
		doSort();
		notifyDataSetChanged();
	}
	
	public void resetDatas(List<T> datasList) {
		if(datasList == null){
			return;
		}
		this.objectList.clear();
		this.objectList.addAll(datasList);
		doSort();
		notifyDataSetChanged();
	}
	
	public void removeData(T item) {
		if(item == null){
			return;
		}
		this.objectList.remove(item);
		notifyDataSetChanged();
	}

	public void cleanListDatasAndNotify() {
		if(objectList != null) {
			objectList.clear();
			notifyDataSetChanged();
		}
	}
	
	public void cleanListDatasOnly() {
		if(objectList != null) {
			objectList.clear();
		}
	}
}